import flet as ft
from services.device_service import DeviceService
from utils.validator import validate_required

class BorrowPage:
    def __init__(self, page):
        self.page = page
        self.service = DeviceService()
        self.build()

    def build(self):
        self.machine_id = ft.TextField(label="机器SN号", hint_text="输入机器唯一标识")
        self.device_type = ft.Dropdown(
            label="设备类型",
            options=[ft.dropdown.Option(t) for t in ["平板", "手表", "手机", "扫描笔"]]
        )
        self.submit_btn = ft.ElevatedButton("提交", on_click=self.submit)

        self.view = ft.Column(
            controls=[
                ft.Text("借出登记", size=24),
                self.machine_id,
                self.device_type,
                self.submit_btn
            ],
            spacing=20
        )

    def submit(self, e):
        try:
            # 前端验证
            if not validate_required([self.machine_id]):
                self.page.show_snack_bar(ft.SnackBar(ft.Text("请填写必填字段!")))
                return

            record = {
                "machine_id": self.machine_id.value,
                "device_type": self.device_type.value,
                "record_type": "借出",
                # 其他字段...
            }
            self.service.create_record(record)
            self.page.show_snack_bar(ft.SnackBar(ft.Text("登记成功!")))
        except Exception as e:
            self.page.show_snack_bar(ft.SnackBar(ft.Text(f"错误: {str(e)}")))
